package com.duapk.index.work;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.AccessControlException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.duapk.index.constant.Constant;


/**
 * 应用关闭监听服务，用于监听ShutDown命令
 * @Package: com.duapk.index.work
 * @ClassName: ShutdownServer
 * @author: jiangzheng
 * @date: Apr 5, 2011 4:53:11 PM
 *
 */
public class ShutdownServer implements Runnable {

	private static Logger logger = LoggerFactory
			.getLogger(ShutdownServer.class);

	/**
	 * 系统监听端口
	 */
	private int port;

	public ShutdownServer(int port) {
		this.port = port;
	}

	/**
	 * 系统退出的命令
	 */
	private static String shutdown = Constant.COMMAND_SHUTDOWN;

	public void run() {
		await();
	}

	public void await() {
		// Set up a server socket to wait on
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port, 1, InetAddress
					.getByName("localhost"));
		} catch (IOException e) {
			logger.error("ShutdownServer.await: create[" + port + "]: ", e);
			System.exit(1);
		}

		// Loop waiting for a connection and a valid command
		while (true) {

			// Wait for the next connection
			Socket socket = null;
			InputStream stream = null;
			try {
				socket = serverSocket.accept();
				socket.setSoTimeout(10 * 1000); // Ten seconds
				stream = socket.getInputStream();
			} catch (AccessControlException ace) {
				logger.warn("ShutdownServer.accept security exception: "
						+ ace.getMessage(), ace);
				continue;
			} catch (IOException e) {
				logger.error("ShutdownServer.await: accept: ", e);
				System.exit(1);
			}

			// Read a set of characters from the socket
			StringBuilder command = new StringBuilder();
			int expected = 1024;
			while (expected > 0) {
				int ch = -1;
				try {
					ch = stream.read();
				} catch (IOException e) {
					logger.warn("ShutdownServer.await: read: ", e);
					ch = -1;
				}
				if (ch < 32) // Control character or EOF terminates loop
					break;
				command.append((char) ch);
				expected--;
			}

			// Close the socket now that we are done with it
			try {
				socket.close();
			} catch (IOException e) {
				;
			}

			// Match against our command string
			boolean match = command.toString().equals(shutdown);
			if (match) {
				break;
			} else
				logger.warn("ShutdownServer.await: Invalid command '"
						+ command.toString() + "' received");

		}

		// Close the server socket and return
		try {
			serverSocket.close();
		} catch (IOException e) {
			;
		}
		// 退出系统
		System.exit(0);
	}
}
